import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Action, Store } from '@ngrx/store';
import { Actions, Effect } from '@ngrx/effects';
import {
    UserActionTypes,
    UserLoadSuccessAction,
    UserLoadFailAction,
    UserAddSuccessAction,
    UserAddFailAction,
    UserUpdateSuccessAction,
    UserUpdateFailAction,
    UserDeleteSuccessAction,
    UserDeleteFailAction,
    UserSearchSuccessAction,
    UserSearchFailAction,
} from '../actions/user.action';
import { toPayload } from '@ngrx/effects/src/util';
import * as fromRoot from '../reducers';
import { Router } from '@angular/router';
import { UserService } from '../services/user.service';
@Injectable()
export class UserEffects {
    @Effect()
    loadUsers$: Observable<Action> = this.actions$
        .ofType(UserActionTypes.LOAD)
        .map(toPayload)
        .switchMap((projectId) => this.service$.getUsersByProject(projectId)
            .map(users => new UserLoadSuccessAction(users))
            .catch(err => Observable.of(new UserLoadFailAction(JSON.stringify(err)))));
    @Effect()
    addUsersProject$: Observable<Action> = this.actions$
        .ofType(UserActionTypes.ADD)
        .map(toPayload)
        .switchMap(({ user, projectId }) => this.service$.addProjectRef(user, projectId)
            .map(u => new UserAddSuccessAction(u))
            .catch(err => Observable.of(new UserAddFailAction(JSON.stringify(err))))
        );

    @Effect()
    updateUsersProjectRef$: Observable<Action> = this.actions$
        .ofType(UserActionTypes.UPDATE)
        .map(toPayload)
        .switchMap((user) => this.service$.batchUpdateProjectRef(user)
            .map(users => new UserUpdateSuccessAction(users))
            .catch(err => Observable.of(new UserUpdateFailAction(JSON.stringify(err)))));
    @Effect()
    delUsersProjectRef$: Observable<Action> = this.actions$
        .ofType(UserActionTypes.DELETE)
        .map(toPayload)
        .switchMap(({ user, projectId }) => this.service$.removeProjectRef(user, projectId)
            .map(u => new UserDeleteSuccessAction(u))
            .catch(err => Observable.of(new UserDeleteFailAction(JSON.stringify(err)))));

    @Effect()
    search$: Observable<Action> = this.actions$
        .ofType(UserActionTypes.SEARCH)
        .map(toPayload)
        .switchMap((str) => this.service$.searchUsers(str)
            .map(users => new UserSearchSuccessAction(users))
            .catch(err => Observable.of(new UserSearchFailAction(JSON.stringify(err)))));
    constructor(
        private actions$: Actions,
        private service$: UserService,
        private store$: Store<fromRoot.State>,
        private router: Router
    ) { }
}
